package com.zzl.mine.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpHelper {

	private static final Logger logger = LoggerFactory.getLogger(HttpHelper.class);
	
	public static String simplePostJson(String url, String paramJsonString) throws Exception {
		return post(url, null, null, paramJsonString, "application/json", "UTF-8");
	}

	public static String simplePostForm(String url, Map<String, String> param) throws Exception {
		return post(url, param, null, null, "application/x-www-form-urlencoded", "UTF-8");
	}

	public static String simplePostXML(String url, String paramXmlString) throws Exception {
		return post(url, null, null, paramXmlString, "application/x-www-form-urlencodedtext/html", "UTF-8");
	}

	public static String post(String url, Map<String, String> param, Map<String, String> headerMap, String entityContent, String contentType, String charset) throws Exception {
		String result = null;
		if (StringUtils.isEmpty(url)) {
			return result;
		}
		
		contentType = StringUtils.isEmpty(contentType) ? "text/html" : contentType;
		charset = StringUtils.isEmpty(charset) ? "UTF-8" : charset;

		PostMethod post = null;
		try {
			post = new PostMethod(url);
			if (StringUtils.isNotEmpty(entityContent)) {
				RequestEntity requestEntity = new StringRequestEntity(entityContent, contentType, charset);
				post.setRequestEntity(requestEntity);
			}
			if (null != param && !param.isEmpty()) {
				Set<String> keySet = param.keySet();
				for (String key : keySet) {
					String v = null == param.get(key) ? "" : param.get(key);
					post.addParameter(key, v);
				}
			}

			/*if(null != param && !param.isEmpty()){
				post.setEntity(new StringEntity(buildQuery(param, charset), charset));
			}*/

			if (null != headerMap && !headerMap.isEmpty()) {
				Set<String> keySet = headerMap.keySet();
				for (String key : keySet) {
					post.addRequestHeader(key, headerMap.get(key));
				}
			}

			HttpClient client = new HttpClient();
			client.getParams().setParameter("http.protocol.content-charset", charset);
			client.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
			client.getHttpConnectionManager().getParams().setSoTimeout(120000);

			int resCode = client.executeMethod(post);
			if (resCode == 200) {
				BufferedReader br = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), charset));
				StringBuffer resBuffer = new StringBuffer();
				String resTemp = "";
				while ((resTemp = br.readLine()) != null) {
					resBuffer.append(resTemp);
				}
				result = StringUtils.trim(resBuffer.toString());

			}
			Header[] headers = post.getRequestHeaders();
			for (Header h : headers) {
				logger.info("请求头参数名称:{},参数值：{}", h.getName(), h.getValue());
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} finally {
			if (null != post) {
				post.releaseConnection();
			}
		}
		return result;
	}

	public static String posttest(String url, Map<String, String> param, Map<String, String> headerMap, String entityContent, String contentType, String charset) throws Exception {
		String result = null;
		if (StringUtils.isEmpty(url)) {
			return result;
		}
		contentType = StringUtils.isEmpty(contentType) ? "text/html" : contentType;
		charset = StringUtils.isEmpty(charset) ? "UTF-8" : charset;

		PostMethod post = null;
		try {
			post = new PostMethod(url);
			if (StringUtils.isNotEmpty(entityContent)) {
				RequestEntity requestEntity = new StringRequestEntity(entityContent, contentType, charset);
				post.setRequestEntity(requestEntity);
			}
			if (null != param && !param.isEmpty()) {
				Set<String> keySet = param.keySet();
				for (String key : keySet) {
					String v = null == param.get(key) ? "" : param.get(key);
					post.addParameter(key, v);
				}
			}

			/*if(null != param && !param.isEmpty()){
				post.setEntity(new StringEntity(buildQuery(param, charset), charset));
			}*/

			if (null != headerMap && !headerMap.isEmpty()) {
				Set<String> keySet = headerMap.keySet();
				for (String key : keySet) {
					post.addRequestHeader(key, headerMap.get(key));
				}
			}

			HttpClient client = new HttpClient();
			client.getParams().setParameter("http.protocol.content-charset", charset);
			client.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
			client.getHttpConnectionManager().getParams().setSoTimeout(120000);

			// int resCode = client.executeMethod(post);
			int resCode = client.executeMethod(post);
			if (resCode == 200) {
				BufferedReader br = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), charset));
				StringBuffer resBuffer = new StringBuffer();
				String resTemp = "";
				while ((resTemp = br.readLine()) != null) {
					resBuffer.append(resTemp);
				}
				result = StringUtils.trim(resBuffer.toString());

			} else if (resCode == 302) {

			}
			Header[] headers = post.getRequestHeaders();
			for (Header h : headers) {
				logger.info("请求头参数名称:{},参数值：{}", h.getName(), h.getValue());
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} finally {
			if (null != post) {
				post.releaseConnection();
			}
		}
		return result;
	}

	public static String buildQuery(Map<String, String> params, String charset) throws IOException {
		List<NameValuePair> nvps = new LinkedList<NameValuePair>();
		for (Entry<String, String> entry : params.entrySet()) {
			nvps.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
		}
		return URLEncodedUtils.format(nvps, charset);
	}

	public static String fetchGetResult(String url, Map<String, String> headerMap, String charset, boolean isFollowRedirects) throws Exception {
		String result = null;
		if (StringUtils.isEmpty(url)) {
			return result;
		}
		charset = StringUtils.isEmpty(charset) ? "UTF-8" : charset;
		GetMethod get = null;
		try {
			get = new GetMethod(url);
			if (null != headerMap && !headerMap.isEmpty()) {
				Set<String> keySet = headerMap.keySet();
				for (String key : keySet) {
					get.addRequestHeader(key, headerMap.get(key));
				}
			}

			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
			client.getHttpConnectionManager().getParams().setSoTimeout(10000);
			get.setFollowRedirects(isFollowRedirects);// 禁止重定向
			int resCode = client.executeMethod(get);
			if (resCode == 200) {
				BufferedReader br = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), charset));
				result = "";
				String line = "";
				while ((line = br.readLine()) != null) {
					result += line;
				}
			} else if ((resCode == 302) && (isFollowRedirects == false)) { // 处理http返回码302的情况
				String locationUrl = get.getResponseHeader("Location").getValue();
				return locationUrl;
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} finally {
			if (null != get) {
				get.releaseConnection();
			}
		}
		return result;
	}

	public static String fetchGetResult(String url, Map<String, String> headerMap, String charset) throws Exception {
		return fetchGetResult(url, headerMap, charset, true);
	}

	public static String fetchGetResult(String url, String charset) throws Exception {
		return fetchGetResult(url, null, charset, true);
	}

}
